package Test_Web;

import java.io.IOException;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mysql.jdbc.PreparedStatement;

/**
 * Servlet implementation class Checkout
 */
public class Checkout extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Checkout() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String firstName = request.getParameter("FirstName");
		String lastName = request.getParameter("LastName");
		String ccId = request.getParameter("CreditCard");
		String expiration = request.getParameter("ExpDate");
		
		// build SQL command
		try
		{
			try {
				Class.forName("com.mysql.jdbc.Driver").newInstance();
			} catch (Exception e) {
				e.printStackTrace();
			}
			Connection connect;
			connect = DriverManager.getConnection("jdbc:mysql:///moviedb","testuser","testpass");
			Statement tempStatement = connect.createStatement();
			String command = "select * from creditcards where first_name = '"+ 
			 firstName+"' AND last_name = '" + lastName + "' AND id = '" + ccId+"' AND expiration = '"+ expiration + 
			"'";
		
			// execute query
			ResultSet resultSet = tempStatement.executeQuery(command);
		
			// if information not valid, prompt to checkout again
			if(!resultSet.isBeforeFirst()) //if invalid password/email
			{
				//redirect back here
				response.sendRedirect("Checkout.jsp");
			}
			// if information is valid, perform checkout
			else
			{
				// find customer id
				Statement tempStatement2 = connect.createStatement();
				String command2 = "select * from customers where cc_id = '" + ccId + "'";
				
				// execute query
				ResultSet resultSet2 = tempStatement.executeQuery(command);
				resultSet2.next();
				String customerID = resultSet2.getString("id");
				
				// get movies in cart
				HttpSession session = request.getSession();
				ArrayList moviesInCartTemp = (ArrayList)session.getAttribute("moviesInCart");
				
				// Make new element for each copy of a movie in the array
				ArrayList moviesInCart = new ArrayList();
				for(int i=0; i<moviesInCartTemp.size(); i++)
				{
					String tempMovieId = (String)moviesInCartTemp.get(i);
					String quantity = tempMovieId.substring(tempMovieId.length()-1, tempMovieId.length());
					String onlyMovieId = tempMovieId.substring(0, tempMovieId.length()-1);
					// add each copy of movie to moviesInCart
					for(int i2=0; i2<Integer.parseInt(quantity); i2++)
					{
						moviesInCart.add(onlyMovieId);
					}
				}
				
				// insert movies into array list
				for(int i=0; i<moviesInCart.size(); i++) //for every entry in moviesInCart
				{
				Statement tempStatement3 = connect.createStatement();
				
				String command3 = "Insert INTO sales (customer_id, movie_id, sale_date) VALUES (" + customerID + ", " +
						(String)moviesInCart.get(i) + ", CURDATE())";
				tempStatement3.executeUpdate(command3);
				}
				
				// Clear Cart
				session.removeAttribute("moviesInCart");
				
				// redirect to main page
				response.sendRedirect("Confirm.html");
			}

			resultSet.close();
            tempStatement.close();
            connect.close();
		}
		catch (SQLException e) {
			e.printStackTrace();
		} 
	}

}
